from pyb import *
class tm1638:
	def __init__(self, DIO, CLK, STB):
		self.tab=[0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F,0x77,0x7C,0x39,0x5E,0x79,0x71]
		self.DIO = DIO
		self.CLK = CLK
		self.STB = STB
		self.DIO.init(Pin.OUT)
		self.CLK.init(Pin.OUT)
		self.STB.init(Pin.OUT)
		self.DIO.high()
		self.CLK.high()
		self.STB.high()
		
		self.write_COM(0x8b)  #亮度 (0x88-0x8f)8级亮度可调
		self.write_COM(0x40)  #采用地址自动加1
		self.STB.low()
		self.write(0xc0)  # 设置起始地址
		for i in range(0, 16):   #传送16个字节的数据
			self.write(0x00)
		self.STB.high()


	def write(self, DATA):	#写数据函数
		self.DIO.init(Pin.OUT)
		for i in range(0, 8):
			self.CLK.low()
			if (DATA&0x01):
				self.DIO.high()
			else:
				self.DIO.low()
			DATA = DATA>>1
			self.CLK.high()
	def read(self):		#//读数据函数
		temp = 0
		self.DIO.init(Pin.IN)
		for i in range(0, 8):
			temp = temp>>1
			self.CLK.low()
			if (self.DIO.value() == 1):
				temp = temp | 0x80
			self.CLK.high()
		return temp
	def write_COM(self, cmd):   #//发送命令字
		self.STB.low()
		self.write(cmd)
		self.STB.high()
		
	def read_key(self):
		c = [0, 0, 0, 0]
		key_value = 0
		self.STB.low()
		self.write(0x42)    # 读键扫数据 命令
		for i in range(0, 4):
			c[i] = self.read()
		self.STB.high()
		for i in range(0, 4):
			key_value = key_value | (c[i]<<i)
		
		return key_value
		
	def write_DATA(self, addr, data):	#指定地址写入数据
		self.write_COM(0x44)
		self.STB.low()
		self.write(0xc0|addr)
		self.write(data)
		self.STB.high()
		
	def write_allLED(self, LED_flag):	  # 控制全部LED函数，LED_flag表示各个LED状态
		for i in range(0, 8):
			if (LED_flag&(1<<i)):
				self.write_DATA(2*i+1, 1);
			else:
				self.write_DATA(2*i+1, 0);

	def write_NUM(self, index, num):
		self.write_DATA(index*2,self.tab[num])
		
	def horseLED(self, delayTime=100):
		for i in range(1, 8):
			self.write_allLED(0x01<<i);
			delay(delayTime)
		
		for i in range(0, 7):
			self.write_allLED(0x01<<(7-i-1));
			delay(delayTime)
	def repeateHorseLED(self, num, delayTime = 100):
		for i in range(0, num):
			self.horseLED(delayTime)
		
def getTM1638():
	return tm1638(Pin("PE4"), Pin("PE3"), Pin("PE2"))
	

	
	





